package com.project.service.impl;

import com.project.bean.UserBean;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Objects;

public class UserServiceImpl extends BaseService implements IUserService {
    @Override
    public UserBean login(String userName, String userPwd) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        UserBean user = mapper.login(userName,userPwd);
        if (userName==null|| userPwd.equals("")){
            return null;
        }
        session.close();
        return user;
    }

    @Override
    public List<UserBean> findAll() {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        List<UserBean> list = mapper.findAll();
        session.close();
        return list;
    }

    @Override
    public UserBean findById(Integer userId) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        UserBean user = mapper.findById(userId);
        session.close();
        return user;
    }

    @Override
    public boolean add(UserBean user) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        List<UserBean> list = mapper.findAll();
        for (int i=0;i<list.size();i++){
            if (user.getUserName().equals(list.get(i).getUserName())){
                return false;
            }
        }
        mapper.add(user);
        session.commit();
        session.close();
        return true;
    }

    @Override
    public void del(Integer userId) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.del(userId);
        session.commit();
        session.close();
    }

    @Override
    public void update(Integer userId, String userGrade) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.update(userId,userGrade);
        session.commit();
        session.close();
    }

    @Override
    public void updatePwd(Integer userId, String userPwd) {
        SqlSession session = this.getSession();
        IUserMapper mapper = session.getMapper(IUserMapper.class);
        mapper.updatePwd(userId,userPwd);
        session.commit();
        session.close();
    }
}
